package com.fishery.logistics.async;

import com.fishery.logistics.entity.vo.LogisticsMessageVo;
import com.fishery.logistics.entity.vo.PathVo;
import com.fishery.logistics.entity.vo.StationVo;
import com.fishery.logistics.mapper.PathMapper;
import com.fishery.logistics.mapper.StationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author run
 * @since 2021/3/14 16:06
 */
@Component
public class LogisticsAsync {

    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private PathMapper pathMapper;

    @Autowired
    private MongoOperations mongoOperations;

    @Async("asyncTaskExecutor")
    public void getStationVoOfId(PathVo pathVo, CountDownLatch count){
        StationVo stationVo = stationMapper.getStationVoById(pathVo.getLogisticsPathStationId());
        pathVo.setLogisticsPathStation(stationVo);
        count.countDown();
    }

    @Async("asyncTaskExecutor")
    public void createPathMessage(String logisticsId){
        LogisticsMessageVo logisticsMessageVo = new LogisticsMessageVo();
        logisticsMessageVo.setLogisticsId(logisticsId);
        List<PathVo> pathVos = pathMapper.getPathVosOfLogistcis(logisticsId);
        logisticsMessageVo.setPaths(pathVos);

        CountDownLatch count = new CountDownLatch(pathVos.size());

        pathVos.forEach(pathVo -> getStationVoOfId(pathVo, count));

        try {
            count.await(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //TODO 获取产品信息
        logisticsMessageVo.setProductMessage(null);

        mongoOperations.insert(logisticsMessageVo);


    }
}
